package com.baobao.action;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.enterprise.inject.New;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;

import com.baobao.domain.Address;
import com.baobao.domain.Askleave;
import com.baobao.domain.Banji;
import com.baobao.domain.Bbevent;
import com.baobao.domain.Chat;
import com.baobao.domain.Notice;
import com.baobao.domain.Parent;
import com.baobao.domain.School;
import com.baobao.domain.Teacher;
import com.baobao.service.AddressService;
import com.baobao.service.AskleaveService;
import com.baobao.service.BanjiService;
import com.baobao.service.BbeventService;
import com.baobao.service.ChatService;
import com.baobao.service.NoticeService;
import com.baobao.service.ParentService;
import com.baobao.service.SchoolService;
import com.baobao.service.StudentService;
import com.baobao.service.TeacherService;
import com.baobao.utility.*;

@Controller
@RequestMapping("/chat")
public class ChatAction {

	private static Logger log = LoggerFactory.getLogger(LeaveAction.class);
	
	@Autowired
	private ParentService parentService;
	
	@Autowired
	private TeacherService teacherService;
	
	@Autowired
	private AddressService addressService;
	
	@Autowired
	private BanjiService banjiService;
	
	@Autowired
	private SchoolService schoolService;
	
	@Autowired
	private ChatService chatService;
	
	/**
	 *获取通讯录列表 
	 */
	@RequestMapping(value="/addresslist",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String GetAddressList(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone){
		
		log.info("获取通讯录列表==>myPhone:"+myPhone);
		JSONArray addressList = new JSONArray();
		
		//查找用户所在的班级（通过家长所绑定的学生-->找到学生所在的班级-->找到所有绑定到此班级的家长信息）
		Set<Address> myAddresses = addressService.findAddressByPhone(myPhone);
		for (Address myAddress : myAddresses) {
			Set<Address> banjiAddresses = addressService.findAddressByBanjiId(myAddress.getBanjiId());
			for (Address eachAddress : banjiAddresses) {
				//用户自己的信息过滤掉
				if(eachAddress.getPhone().equals(myPhone))
				{
					continue;
				}
				JSONObject addressJsonObject = new JSONObject();
				addressJsonObject.put("phone", eachAddress.getPhone());
				addressJsonObject.put("imgUrl", eachAddress.getImgUrl());
				
				Parent parent = parentService.findParentByPrimaryKey(eachAddress.getPhone());
				addressJsonObject.put("name", parent.getName());
				
				Banji banji = banjiService.findBanjiByPrimaryKey(eachAddress.getBanjiId());
				School school = schoolService.findSchoolByPrimaryKey(banji.getSchoolId());
				addressJsonObject.put("banji", banji.getName());
				addressJsonObject.put("teacherPhone", banji.getMasterPhone());
				addressJsonObject.put("teacherName", banji.getMasterName());
				addressJsonObject.put("school", school.getName());
				addressList.add(addressJsonObject);
			}
		}
		
		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("message",addressList);
		log.info("应答通讯录列表：" + result.toString());
		return result.toString();
	}
	
	/**
	 *最近联系人列表
	 */
	@RequestMapping(value="/latestContactor",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String GetLatestContactor(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone){
		
		log.info("获取最近联系人列表==>myPhone:"+myPhone);
		JSONArray addressList = new JSONArray();
		JSONArray banjiList = new JSONArray();
		//查找用户所在的班级（通过家长所绑定的学生-->找到学生所在的班级-->找到所有绑定到此班级的家长信息）
		Set<Address> myAddresses = addressService.findAddressByPhone(myPhone);
		
		for (Address myAddress : myAddresses) {
			
			//获取班级群组列表
			Banji banji = banjiService.findBanjiByPrimaryKey(myAddress.getBanjiId());
			JSONObject banjiJsonObject = new JSONObject();
			banjiJsonObject.put("name", banji.getName());
			banjiJsonObject.put("id", banji.getId());
			School school = schoolService.findSchoolByPrimaryKey(banji.getSchoolId());
			banjiJsonObject.put("school",school.getName());
			banjiList.add(banjiJsonObject);
			
			Set<Address> banjiAddresses = addressService.findAddressByBanjiId(myAddress.getBanjiId());
			for (Address eachAddress : banjiAddresses) {
				//用户自己的信息过滤掉
				if(eachAddress.getPhone().equals(myPhone))
				{
					continue;
				}
				//依次查找与每个成员的聊天记录(发送者电话、接收者电话)
				Set<Chat> chats = chatService.findChatByMaxDateAndPhone(eachAddress.getPhone(),myPhone);
				Chat chat = null;
				for (Chat chatTmp : chats) {
					chat = chatTmp;
				}
				
				if(chat != null){
					JSONObject addressJsonObject = new JSONObject();
					addressJsonObject.put("phone", eachAddress.getPhone());
					addressJsonObject.put("imgUrl", eachAddress.getImgUrl());
					
					Parent parent = parentService.findParentByPrimaryKey(eachAddress.getPhone());
					addressJsonObject.put("name", parent.getName());
					
					Calendar calendat = Calendar.getInstance();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					addressJsonObject.put("date", sdf.format(chat.getDate().getTime()));
					addressJsonObject.put("latestMsg", chat.getText());
					addressList.add(addressJsonObject);
				}
			}
		}
		
		JSONObject contactorList = new JSONObject();
		contactorList.put("group", banjiList);
		contactorList.put("contactor", addressList);
		
		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("message",contactorList);
		log.info("最近联系人列表：" + result.toString());
		return result.toString();
	}
	
	/**
	 *获取通讯录列表 
	 */
	@RequestMapping(value="/userlist",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String GetUserList(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone){
		
		log.info("获取通讯录列表==>myPhone:"+myPhone);
		JSONArray parentList = new JSONArray();
		JSONArray teacherList = new JSONArray();
		
		//查找用户所在的班级（通过家长所绑定的学生-->找到学生所在的班级-->找到所有绑定到此班级的家长信息）
		Set<Address> myAddresses = addressService.findAddressByPhone(myPhone);
		for (Address myAddress : myAddresses) {
			//获取老师列表
			Set<Teacher> teachers = teacherService.findTeacherByBanjiId(myAddress.getBanjiId());
			for(Teacher teacher : teachers){
				if(teacher.getPhone().equals(myPhone))
				{
					continue;
				}
				JSONObject teacherJsonObject = new JSONObject();
				teacherJsonObject.put("phone",teacher.getPhone());
				teacherJsonObject.put("imgUrl", teacher.getImgUrl());
				teacherJsonObject.put("name", teacher.getName());
				teacherList.add(teacher);
			}
			
			//获取家长列表
			Set<Address> banjiAddresses = addressService.findAddressByBanjiId(myAddress.getBanjiId());
			for (Address eachAddress : banjiAddresses) {
				
				if(eachAddress.getPhone().equals(myPhone))
				{
					continue;
				}
				JSONObject addressJsonObject = new JSONObject();
				addressJsonObject.put("phone", eachAddress.getPhone());
				addressJsonObject.put("imgUrl", eachAddress.getImgUrl());
				
				Parent parent = parentService.findParentByPrimaryKey(eachAddress.getPhone());
				addressJsonObject.put("name", parent.getName());
				
				Banji banji = banjiService.findBanjiByPrimaryKey(eachAddress.getBanjiId());
				School school = schoolService.findSchoolByPrimaryKey(banji.getSchoolId());
				addressJsonObject.put("banji", banji.getName());
				addressJsonObject.put("teacherPhone", banji.getMasterPhone());
				addressJsonObject.put("teacherName", banji.getMasterName());
				addressJsonObject.put("school", school.getName());
				parentList.add(addressJsonObject);
			}
		}
		
			
		JSONObject userList = new JSONObject();
		userList.put("teacher", teacherList);
		userList.put("parent", parentList);
		
		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("message",userList);
		log.info("应答通讯录列表：" + result.toString());
		return result.toString();
	}
	
	
	/**
	 * 发送一条消息
	 */
	@RequestMapping(value="/send",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String SubmitSendMsg(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone,
		@RequestParam(value="yourPhone",required=true) String yourPhone,
		@RequestParam(value="text",required=true) String text,
		@RequestParam(value="date",required=true) String date){
		
		log.info("发送一条聊天信息==>myPhone:"+myPhone+";yourPhone:"+yourPhone+";text:"+text+";date"+date);
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			Date sendDate =sdf.parse(date);
			calendar.setTime(sendDate);			

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		int uniqueId = (int) Math.round(Math.random()*10000);
		Chat chat = new Chat();
		chat.setReceiver(yourPhone);
		chat.setSender(myPhone);
		chat.setStatus("unSeen");
		chat.setText(text);
		chat.setDate(calendar);
		chat.setUniqueId(uniqueId);
		chatService.saveChat(chat);
				
		JSONObject result = new JSONObject();
		result.put("success", true);
		return result.toString();
	}
	
	/**
	 * 获取最新N条消息
	 */
	@RequestMapping(value="/readlatest",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String ReadLatestNewMsg(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone,
		@RequestParam(value="yourPhone",required=true) String yourPhone,
		@RequestParam(value="msgnum",required=true) String msgnum){
		
		log.info("获取近期聊天消息==>myPhone:"+myPhone+";yourPhone:"+yourPhone + ";msgnum:"+msgnum);
		JSONArray jsonarray = new JSONArray();
//		JSONObject left = new JSONObject();
//		JSONObject right = new JSONObject();
//		int uniqueId = (int) Math.round(Math.random()*10000);
//		left.put("text", "欢迎使用React-Native来构建聊天程序:"+uniqueId);
//		left.put("name","chocolate");
//		left.put("image", null);
//		left.put("position", "left");
//		left.put("date",new Date());
//		left.put("uniqueId", uniqueId);
//		jsonarray.add(left);
//		
//		uniqueId = (int) Math.round(Math.random()*10000);
//		right.put("text", "是的，我正在使用Gifted Messenger:"+uniqueId);
//		right.put("name","lasagoo");
//		right.put("image", null);
//		right.put("position", "right");
//		right.put("date",new Date());
//		right.put("uniqueId", uniqueId);
//		jsonarray.add(right);
		
		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("message", jsonarray);
		return result.toString();
	}
	
	/**
	 * 获取最新N条群聊消息（打开群聊窗口时调用）
	 */
	@RequestMapping(value="/latestGroupMsg",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String ReadLatestGroupMsg(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone,
		@RequestParam(value="yourPhone",required=true) String yourPhone,  //此处yourphone代表的是banjiId
		@RequestParam(value="startDate",required=true) String startDateStr,  //此处yourphone代表的是banjiId
		@RequestParam(value="msgnum",required=true) String msgnum){
		
		log.info("获取近期"+msgnum+"条群聊消息==>yourPhone:"+yourPhone + "start_date:"+startDateStr);
		JSONArray chatJsonArray = new JSONArray();

		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			Date startDate =sdf.parse(startDateStr);
			calendar.setTime(startDate);			

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Set<Chat> chatList = chatService.findChatByReceiverAndLatestMsgnum(yourPhone, calendar,Integer.parseInt(msgnum));
		for (Chat chat : chatList) {
			
			JSONObject message = new JSONObject();
				
			Parent parent = parentService.findParentByPrimaryKey(chat.getSender());
			Address address = addressService.findAddressByPrimaryKey(chat.getSender(), yourPhone);//根据phone和banjiid获取address
			message.put("name",parent.getName());
			message.put("text", chat.getText());
			if(address != null) message.put("image",address.getImgUrl());
			
			//如果是本人发送的群组消息，放在右侧；其他人发送的，放在左侧;
			if(myPhone.equals(chat.getSender()))
			{
				message.put("position", "right");
			}
			else{
				message.put("position", "left");
			}
			message.put("date",chat.getDate().getTime());
			message.put("dateStr",sdf.format(chat.getDate().getTime()));
			message.put("uniqueId", chat.getUniqueId());
			chatJsonArray.add(message);
			
			chat.setStatus("Seen");
			chatService.saveChat(chat);
		}
		
		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("message", chatJsonArray);
		return result.toString();
	}
	
	/**
	 * 获取最新未读消息
	 */
	@RequestMapping(value="/readnew",produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String ReadLatestNewMsg(HttpServletRequest request,
		@RequestParam(value="myPhone",required=true) String myPhone,
		@RequestParam(value="yourPhone",required=true) String yourPhone){
		
		log.info("获取最新未读聊天消息==>myPhone:"+myPhone+";yourPhone:"+yourPhone);
		
		Set<Chat> chatList = chatService.findChatByPhoneAndStatus(yourPhone, myPhone, "unSeen");
		
		JSONObject result = new JSONObject();
		if(chatList.size() == 0)
		{
			result.put("success", false);
			result.put("error", "没有新消息");
			return result.toString();
		}
		//int uniqueId = (int) Math.round(Math.random()*10000);
		JSONArray chatJsonArray = new JSONArray();
		for (Chat chat : chatList) {
			JSONObject message = new JSONObject();
				
			Parent parent = parentService.findParentByPrimaryKey(chat.getSender());
			message.put("name",parent.getName());
			message.put("text", chat.getText());
			message.put("image", null);
			message.put("position", "left");
			message.put("date",chat.getDate().getTime());
			message.put("uniqueId", chat.getUniqueId());
			chatJsonArray.add(message);
			
			chat.setStatus("Seen");
			chatService.saveChat(chat);
		}
	
		
		result.put("success", true);
		result.put("message", chatJsonArray);
		log.info("最新未读消息为："+result.toString());
		return result.toString();
	}

}
